package com.aaa.service.impl;

import com.aaa.dao.RoleDao;
import com.aaa.entity.Role;
import com.aaa.service.RoleService;
import com.aaa.util.DateUtil;
import com.aaa.util.DefaultMsg;
import com.aaa.util.TableData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 角色管理service实现类
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;

    public TableData<Role> page(String keyword, Integer page, Integer limit) {
        TableData<Role> tableData = new TableData<Role>();
        //第一步，查询当前页的数据
        Integer offset = (page-1)*limit;
        List<Role> data = roleDao.listPage(keyword,offset, limit);
        tableData.setData(data);
        //第二步，查询总条数
        Integer count = roleDao.count(keyword);
        tableData.setCount(count);
        return tableData;
    }
    public DefaultMsg saveOrUpdate(Role role,String rids) {
        DefaultMsg defaultMsg = new DefaultMsg();
        Integer count;
        Long rid =role.getId();
        if(rid==null){
            role.setCreateDate(DateUtil.getCurrentDate());
            //保存角色
            rid=roleDao.save(role);
        }else {
            count=roleDao.update(role);
            if(count==0){
                throw  new RuntimeException("保存用户角色失败");
            }
            //删除角色原先能操作的模块
            count = roleDao.deleteRoleMenu(rid);
        }
        //保存角色能操作的菜单
        for(String ridStr : rids.split(",")){
            count = roleDao.saveRoleMenu(rid,Long.valueOf(ridStr));
            if(count==0){
                throw  new RuntimeException("保存用户角色失败");
            }
        }
        return defaultMsg;
    }

    public List<Role> listAll() {
        return roleDao.listAll();
    }

    public List<Role> listUserRoles(Long uid) {
        return roleDao.listUserRoles(uid);
    }
}
